package com.woniuxy.lab.woniu_lab_boss.util;


import com.woniuxy.lab.woniu_lab_boss.exception.AccountException;
import com.woniuxy.lab.woniu_lab_boss.exception.WebExceptionCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.http.HttpServletRequest;
;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtil {
    public static final String LAP_BOSS_TOKEN = "lap-boss-token";
    public static final long DAY = 1000L * 60 * 60 * 24;
    public static final String ACCOUNT_ID = "accountId";
    public static final String TYPE = "type";
    public static final String PERSON_ID = "person_id";
    //
    /**
     * 盐可以定义在springboot配置文件中，通过@ConfigurationProperties注解去读取
     */
    static String secret="qwertyuiopasdfghjklzxcvbnm!@#$%^&*()";

    /**
     * 1.用于创建令牌的方法
     */
    public static String getToken(Map claims, Integer days){
        Key key = Keys.hmacShaKeyFor(secret.getBytes());
        return Jwts.builder()
                //向payload中保存数据
            .setClaims(claims)
                //设置令牌的过期时间,令牌的过期时间一定要大于当前系统时间
            .setExpiration(new Date(System.currentTimeMillis() + (DAY * days)))
                //加盐
            .signWith(key)
            .compact();
    }

    /**
     * 2.用于解析令牌的方法
     * @param token 令牌
     * @return 解析后的令牌
     */
    public static Claims parseToken(String token){
        Key key = Keys.hmacShaKeyFor(secret.getBytes());
        Claims claims = null;
        try {
            claims = Jwts.parserBuilder()
                    //使用指定的盐
                    .setSigningKey(key)
                    //创建解析令牌的对象
                    .build()
                    //解析令牌
                    .parseClaimsJws(token)
                    //获取载荷中保存的内容
                    .getBody();
        }catch (ExpiredJwtException e){
            throw new AccountException(WebExceptionCode.JWT_EXPIRED);
        }

        return claims;

    }

    /**
     * 从令牌中获取账号id
     */
    public static Integer getUserIdFromReq(){
        // 获取token
        String token = getTokenFromReq();
        return (Integer) parseToken(token).get(ACCOUNT_ID);
    }

    /**
     *  从令牌中获取用户类型
     */
    public static String getUserTypeFromReq(){
        // 获取token
        String token = getTokenFromReq();

        return (String) parseToken(token).get(TYPE);
    }

    /**
     *  从令牌中获取person_id
     */
    public static Integer getUserPersonFromReq(){
        // 获取token
        String token = getTokenFromReq();
        return (Integer) parseToken(token).get(PERSON_ID);
    }

    /**
     * 从请求头中获取token
     */
    public static String getTokenFromReq(){
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader(LAP_BOSS_TOKEN);
        return token;
    }


}
